﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using IDAL;
using Models;

namespace DAL
{
    public class LinksInfoDAL:ILinksInfo
    {

        private const string SQL_TOPFOUR_LinklInfo = @"select top 4 * from LinksInfo order by PicLevel desc";

        public DataBase DB = new DataBase();

        public List<LinksInfo> GetTopFourLinksInfo()
        {
            List<LinksInfo> list = new List<LinksInfo>();
            DB.DatabaseConnection();
            SqlDataReader reader = DB.GetdataRecords(SQL_TOPFOUR_LinklInfo);
            while (reader.Read())
            {
                LinksInfo linksInfo = new LinksInfo();
                ReadtoLinksInfo(reader, linksInfo);
                list.Add(linksInfo);
            }
            DB.CloseDB();
            return list;
        }
        public List<LinksInfo> GetLinksInfo()
        {
            string sql = " SELECT * FROM LinksInfo order by PicLevel desc";
            List<LinksInfo> list = new List<LinksInfo>();
            DB.DatabaseConnection();
            SqlDataReader reader = DB.GetdataRecords(sql);
            while (reader.Read())
            {
                LinksInfo linksInfo = new LinksInfo();
                ReadtoLinksInfo(reader, linksInfo);
                list.Add(linksInfo);
            }
            DB.CloseDB();
            return list;
        }
        public int UpdateLinksInfo(LinksInfo link)
        {
            string sql = "UPDATE LinksInfo SET LinkURL = '" + link.LinkURL + "', LinkPicURL = '" + link.LinkPicURL + "', PicLevel=" + link.PicLevel + " WHERE LinkID =" + link.LinkID;
            return DB.UpdateRecords(sql);
        }
        public int InsertLinksInfo(LinksInfo link)
        {
            string sql = "INSERT INTO LinksInfo([LinkURL],[LinkPicURL],[PicLevel]) VALUES('" + link.LinkURL + "','" + link.LinkPicURL + "'," + link.PicLevel + ")";
            return DB.UpdateRecords(sql);
        }
        public int DeleteLinksInfo(LinksInfo link)
        {
            string sql = "DELETE FROM LinksInfo WHERE LinkID = " + link.LinkID;
            return DB.UpdateRecords(sql);
        }
        public void ReadtoLinksInfo(SqlDataReader reader, LinksInfo linksInfo)
        {
            try
            {
                linksInfo.LinkID = Int32.Parse(reader["LinkID"].ToString());
            }
            catch
            {
                //linksInfo.LinkID = 1;
            }
            
            linksInfo.LinkURL =reader["LinkURL"] is DBNull?"":reader["LinkURL"].ToString();
            linksInfo.LinkPicURL =reader["LinkPicURL"] is DBNull?"":reader["LinkPicURL"].ToString();

            try
            {
                linksInfo.PicLevel = Int32.Parse(reader["PicLevel"].ToString());
            }
            catch
            {

            } 
        }
    }
}
